import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

export interface TabItem {
  path: string
  title: string
  icon?: string
}

export const useTabsStore = defineStore(
  'tabs',
  () => {
    const tabs = ref<TabItem[]>([
      {
        path: '/dashboard',
        title: '看板',
        icon: 'DashboardOutlined',
      },
    ])

    const activeTab = ref<string>('/dashboard')

    // 添加标签页
    const addTab = (route: RouteLocationNormalizedLoaded) => {
      // 只添加有 keepAlive 的页面
      if (!route.meta.keepAlive) return

      const exists = tabs.value.some((tab) => tab.path === route.path)
      if (!exists) {
        tabs.value.push({
          path: route.path,
          title: (route.meta.title as string) || '未命名',
          icon: route.meta.icon as string,
        })
      }
      activeTab.value = route.path
    }

    // 移除标签页
    const removeTab = (path: string) => {
      const index = tabs.value.findIndex((tab) => tab.path === path)
      if (index > -1) {
        tabs.value.splice(index, 1)
      }
    }

    // 关闭其他标签页
    const closeOtherTabs = (path: string) => {
      tabs.value = tabs.value.filter((tab) => tab.path === path || tab.path === '/dashboard')
    }

    // 关闭所有标签页（除了首页）
    const closeAllTabs = () => {
      tabs.value = tabs.value.filter((tab) => tab.path === '/dashboard')
      activeTab.value = '/dashboard'
    }

    return {
      tabs,
      activeTab,
      addTab,
      removeTab,
      closeOtherTabs,
      closeAllTabs,
    }
  },
  {
    // 启用持久化
    persist: {
      enabled: true,
      strategies: [
        {
          key: 'admin_tabs',
          storage: localStorage,
          paths: ['tabs', 'activeTab'],
        },
      ],
    },
  }
)
